<?php

namespace app\api\controller;

use app\lib\exception\ParameterException;
use app\lib\Qiniu;
use app\common\BaseHelper;

use app\admin\model\Image;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 通用
 */
class Common extends BaseController
{

    /**
     * 上传图片
     */
    public function uploadOneImg() {
        $param = self::getHttpParam();

        /*if (empty($param->imgUrl)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'imgUrl 不能为空');
        }*/
        if (empty($_FILES['images'])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'images 不能为空');
        }

        $Qiniu = new Qiniu();
        $upload = $Qiniu->postDoupload($_FILES['images']);
        if($upload['status'] == 'fail') {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, $upload['message']);
        }
        $data = [
            'id' => BaseHelper::getUUID(),
            'imgUrl' => config('qiniu.image_url') . $upload['key'],
            'created' => time(),
            //'relatedTable' => ''
        ];
        $result = Image::insert($data);
        if($result !== false) {
            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
        } else {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '上传失败！');
        }
    }

    /**
     * 删除单张图片
     */
    public function delOneImg() {
        $param = self::getHttpParam();

        /*if (empty($param->imgId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'imgId 不能为空');
        }*/
        if (empty($param->imgUrl)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'imgUrl 不能为空');
        }

        //$id = $param->imgId;
        $url = $param->imgUrl;
        $key = substr(strrchr($url, '/'), 1);
        $Qiniu = new Qiniu();
        // 删除七牛图片
        $result = $Qiniu->delImg($key);
        if($result == NULL){
            db('image')->where('imgUrl', $url)->delete();

            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '删除成功！');
        }else{
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '删除失败！');
        }
    }

}